package com.xiaomengkuan.common.handler;

import com.xiaomengkuan.common.exception.CasualException;
import com.xiaomengkuan.common.exception.LoginFailedException;
import com.xiaomengkuan.common.exception.RequestBodyArgumentException;
import com.xiaomengkuan.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Faraj Mujey
 * -- Creation Time: 2021-01-25 10:51 下午, File Encoding: utf8 --
 * 全局异常处理
 */
@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = LoginFailedException.class)
    public R exceptionHandler(LoginFailedException e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception" +
                "（登陆失败，用户名、密码错误）");
        return R.err().detail(e.getMessage());
    }

    @ExceptionHandler(value = RequestBodyArgumentException.class)
    public R exceptionHandler(RequestBodyArgumentException e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception" +
                        "（请求体参数异常）:" +
                        " {}",
                e.getMessage());
        return R.err().detail(e.getMessage());
    }

    @ExceptionHandler(value = CasualException.class)
    public R exceptionHandler(CasualException e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception: {}",
                e.getMessage());
        return R.err().detail(e.getMessage());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public R exceptionHandler(NullPointerException e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception: " +
                "NullPointerException（空指针异常）");
        return R.err().detail("NullPointerException");
    }

    @ExceptionHandler(value = IllegalAccessException.class)
    public R exceptionHandler(IllegalAccessException e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception: " +
                "IllegalAccessException（非法访问异常）");
        return R.err().detail("IllegalAccessException");
    }


    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e) {
        e.printStackTrace();
        log.warn("Execution global exception handler, catch Exception: {}",
                e.getMessage());
        return R.err().detail(e.getMessage());
    }
}
